package com.example.mybatisplusdemo.web.controller;

import com.example.mybatisplusdemo.model.domain.ItineraryRequest;
import com.example.mybatisplusdemo.service.FlightSearchService;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.example.mybatisplusdemo.common.JsonResponse;
import com.example.mybatisplusdemo.model.domain.Flight;

import java.time.Duration;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;


/**
 *
 *  前端控制器
 *
 *
 * @author yzy
 * @since 2025-07-07
 * @version v1.0
 */
@RestController
@RequestMapping("/api/flights")
public class FlightSearchController {

    private final FlightSearchService flightSearchService;

    @Autowired
    public FlightSearchController(FlightSearchService flightSearchService) {
        this.flightSearchService = flightSearchService;
    }

    @PostMapping("/search")
    public JsonResponse<Object> searchFlights(@RequestBody ItineraryRequest request) {
        try {
            List<Flight> flights = flightSearchService.searchFlights(request);
            return JsonResponse.success(flights, "航班搜索成功");
        } catch (Exception e) {
            return JsonResponse.failure("航班搜索失败: " + e.getMessage())
                    .setCode(500)
                    .setException(e);
        }
    }

    @PostMapping("/recommend")
    public JsonResponse<Object> recommendFlights(
            @RequestBody ItineraryRequest request,
            @RequestParam(required = false) String sort,
            @RequestParam(required = false, defaultValue = "asc") String order) {

        try {
            List<Flight> flights = flightSearchService.searchFlights(request);
            flights = applySorting(flights, sort, order);
            return JsonResponse.success(flights, "智能推荐成功");
        } catch (Exception e) {
            return JsonResponse.failure("推荐失败: " + e.getMessage())
                    .setCode(500)
                    .setException(e);
        }
    }

    private List<Flight> applySorting(List<Flight> flights, String sort, String order) {
        if (sort == null) return flights;

        Comparator<Flight> comparator = switch (sort.toLowerCase()) {
            case "duration" -> Comparator.comparing(f ->
                    Duration.between(f.getDepartureTime(), f.getArrivalTime()));
            case "punctuality" -> Comparator.comparing(Flight::getPunctualityRate);
            case "carbon" -> Comparator.comparing(Flight::getCarbonEmission);
            default -> Comparator.comparing(Flight::getPrice);
        };

        if ("desc".equalsIgnoreCase(order)) {
            comparator = comparator.reversed();
        }

        return flights.stream()
                .sorted(comparator)
                .collect(Collectors.toList());
    }
}

